import React, { useState, useEffect } from 'react';
import './EditGroupNameModal.css';

interface EditGroupNameModalProps {
  isOpen: boolean;
  currentGroupName: string;
  onClose: () => void;
  onSave: (newName: string) => void;
}

const EditGroupNameModal: React.FC<EditGroupNameModalProps> = ({
  isOpen,
  currentGroupName,
  onClose,
  onSave,
}) => {
  const [groupName, setGroupName] = useState(currentGroupName);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setGroupName(currentGroupName);
    }
  }, [isOpen, currentGroupName]);

  const handleSave = async () => {
    if (!groupName.trim()) {
      alert('群名称不能为空');
      return;
    }

    if (groupName.trim() === currentGroupName) {
      onClose();
      return;
    }

    setIsLoading(true);
    try {
      await onSave(groupName.trim());
      onClose();
    } catch (error) {
      console.error('修改群名称失败:', error);
      alert('修改群名称失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSave();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="edit-group-name-modal-overlay">
      <div className="edit-group-name-modal">
        <div className="modal-header">
          <button className="cancel-btn" onClick={onClose}>
            取消
          </button>
          <h3 className="modal-title">修改群名称</h3>
          <button
            className="save-btn"
            onClick={handleSave}
            disabled={isLoading || !groupName.trim()}
          >
            {isLoading ? '保存中...' : '保存'}
          </button>
        </div>

        <div className="modal-content">
          <div className="input-group">
            <label className="input-label">群名称</label>
            <input
              type="text"
              value={groupName}
              onChange={e => setGroupName(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入群名称"
              className="group-name-input"
              maxLength={20}
              autoFocus
            />
            <div className="char-count">{groupName.length}/20</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EditGroupNameModal;
